package ops

import (
	"errors"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/util/gconv"
	"snake/library/base"
	"snake/app/model/ops"
	"fmt"
	"encoding/json"
)

// 请求参数
type Request struct {
	Job *ops.Job
	UserId int `form:"userId" json:"userId"`
}

// 通过id获取实体
func GetById(id int64) (*ops.Job, error) {
	if id <= 0 {
		glog.Error(" get id error")
		return new(ops.Job), errors.New("参数不合法")
	}
	where := fmt.Sprintf(" id = '%d' ", id)
	var resData ops.Job
	var tasks []ops.Task

	var rmap map[string]interface{}
	dbModel := ops.Model.As("t").Fields(ops.Model.Columns()+ ",sc.name as scriptName").LeftJoin("script sc", " t.script_id = sc.id ")
	result, err := dbModel.M.Select(where)
	if err != nil {
		glog.Error(err)
		return new(ops.Job), err
	}
	//转map
	rmap = gconv.Map(result.ToList()[0])
	//tasks字段由json转为[]*Task结构体
	json.Unmarshal([]byte(gconv.String(rmap["tasks"])), &tasks)
	rmap["tasks"] = tasks
	err = gconv.Struct(rmap, &resData)
	if err != nil {
		glog.Error(err)
		return new(ops.Job), err
	}
	return &resData, nil
}

// 通过id获取实体
func GetByJobId(jobId string) (*ops.Job, error) {
	if jobId == "" {
		glog.Error(" get jobId error")
		return new(ops.Job), errors.New("参数不合法")
	}
	where := fmt.Sprintf(" job_id = '%s' ", jobId)
	var resData ops.Job
	var tasks []ops.Task

	var rmap map[string]interface{}
	dbModel := ops.Model.As("t").Fields(ops.Model.Columns()+ ",sc.name as scriptName").LeftJoin("script sc", " t.script_id = sc.id ")
	result, err := dbModel.M.Select(where)
	if err != nil {
		glog.Error(err)
		return new(ops.Job), err
	}
	//转map
	rmap = gconv.Map(result.ToList()[0])
	//tasks字段由json转为[]*Task结构体
	json.Unmarshal([]byte(gconv.String(rmap["tasks"])), &tasks)
	rmap["tasks"] = tasks
	err = gconv.Struct(rmap, &resData)
	if err != nil {
		glog.Error(err)
		return new(ops.Job), err
	}
	return &resData, nil
}

// 删除实体
func Delete(id int64, userId int) (int64, error) {
	if id <= 0 {
		glog.Error("delete id error")
		return 0, errors.New("参数不合法")
	}
	r, err1 := ops.Model.Delete(" id = ?", id)
	if err1 != nil {
		return 0, err1
	}
	return r.RowsAffected()
}

// 保存实体
func Save(request *Request) (int64, error) {
	entity := (*ops.Job)(nil)
	err := gconv.Struct(request.Job, &entity)
	if err != nil {
		return 0, errors.New("数据错误")
	}
	// 判断新增还是修改
	if entity.Id <= 0 {
		// glog.Info("新增数据:", entity)
		r, err := ops.Model.Insert(entity)
		if err != nil {
			glog.Error("新增数据失败:", err)
			return 0, err
		}
		// 回写主键
		lastId, err := r.LastInsertId()
		if err != nil {
			glog.Error(err)
			return 0, err
		}
		entity.Id = gconv.Int(lastId)
		return r.RowsAffected()
	} else {
		// glog.Debug("更新数据:", entity)
		r, err := ops.Model.OmitEmpty().Where(" id = ?", entity.Id).Update(entity)
		if err != nil {
			glog.Error(err)
			return 0, err
		}
		return r.RowsAffected()
	}
}

// 分页查询
func Page(form *base.BaseForm) ([]ops.Job, error) {
	if form.Page <= 0 || form.Rows <= 0 {
		glog.Error("page param error", form.Page, form.Rows)
		return []ops.Job{}, nil
	}
	where := " 1 = 1 "
	var params []interface{}
	if form.Params != nil && form.Params["scriptId"] != "" {
		where += " and script_id = "
		params = append(params, form.Params["scriptId"])
	}
	num, err := ops.Model.As("t").FindCount(where, params)
	form.TotalSize = num
	form.TotalPage = num / form.Rows
	if err != nil {
		glog.Error("page count error", err)
		return []ops.Job{}, err
	}
	// 没有数据直接返回
	if num == 0 {
		form.TotalPage = 0
		form.TotalSize = 0
		return []ops.Job{}, err
	}
	dbModel := ops.Model.As("t").Fields(ops.Model.Columns() + ",sc.name as scriptName").LeftJoin("script sc", " t.script_id = sc.id ").Order(form.OrderBy).Page(form.Page, form.Rows)
	//dbModel = dbModel.LeftJoin("script sc", " t.script_id = sc.id ")
	result, err := dbModel.M.Select(where, params)
	if err != nil {
		glog.Error("page list error", err)
		return []ops.Job{}, err
	}

	var resData []ops.Job
	//遍历
	ljob := result.ToList()
	for _, item := range ljob {
		var job ops.Job
		var tasks []ops.Task
		json.Unmarshal([]byte(gconv.String(item["tasks"])), &tasks)
		item["tasks"] = tasks
		//tasks字段由json转为[]*Task结构体
		err = gconv.Struct(item, &job)
		if err != nil {
			glog.Error("convert map to ops.Job{} error, ", err.Error())
		}
		resData = append(resData, job)
	}
	//err = dbModel.Where(where, params).Order(form.OrderBy).Page(form.Page, form.Rows).M.Structs(&resData)
	return resData, nil
}


// func main(){
// 	//m := make(map[string]interface{},0)
// 	//form := base.NewForm(m)
// 	//Page(&form)
// 	res, _ := GetByJobId("4fa79a97-8ed8-4c7d-8201-a204cc2bac46")
// 	data, err := json.Marshal(res)
// 	fmt.Print(string(data))
// 	fmt.Print(err)
// }